package org.springblade.modules.serial;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class WriteTimeoutDetectionHandler extends ChannelDuplexHandler {
    private static final Logger logger = LoggerFactory.getLogger(WriteTimeoutDetectionHandler.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        // 所有写入操作都会经过这里，自动重置IdleStateHandler的写空闲计时器
		logger.info("客户端 {} 写入数据，重置写超时计时器", ctx.channel().remoteAddress());
        super.write(ctx, msg, promise);

        // 记录调试信息
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.WRITER_IDLE) {
                // 写空闲超时处理
                logger.info("客户端 {} 超过 {} 秒未写入，即将断开连接",
                          ctx.channel().remoteAddress(),
                          30);
                ctx.close().sync();
                ctx.flush();
            }
        }
//        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("连接异常: {}", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }
}
